package com.woniuxy.tfss.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.woniuxy.tfss.entity.ResponseEntity;
import com.woniuxy.tfss.exception.TokenExpiredException;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


public class JwtFilter extends AuthenticationFilter {
    @Autowired
    private Audience audience;
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (audience == null) {
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            audience = (Audience) factory.getBean("audience");
        }
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("token");
        if (token == null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                String value = mapper.writeValueAsString(ResponseEntity.UNLOGIN);
                response.getWriter().print(value);
                response.getWriter().close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            return false;
        }
        try {
            Boolean t = JwtTokenUtil.parseJwt(token, audience.getBase64Secret());
            if (t) {
                return true;
            }
            return false;
        } catch (Exception e) {
            if (e instanceof TokenExpiredException) {
                ObjectMapper mapper = new ObjectMapper();
                try {
                    String value = mapper.writeValueAsString(ResponseEntity.OVERTIME);
                    response.getWriter().print(value);
                    response.getWriter().close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
                return false;
            } else {
                ObjectMapper mapper = new ObjectMapper();
                try {
                    String value = mapper.writeValueAsString(ResponseEntity.FAIL);
                    response.getWriter().print(value);
                    response.getWriter().close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
                return false;
            }
        }
    }
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().print(mapper.writeValueAsString(ResponseEntity.FORBIDDEN));
        response.getWriter().close();
        return false;
    }
}
